import requests
from datetime import datetime, timedelta
from urllib.parse import quote_plus
from mysqldbhelper import MysqldbHelper

# 假设这是你的URL
url_prefix = 'http://10.10.3.125:12345/dolphinscheduler'

# 假设这是你获取到的Token
token = 'c8d94a42cd1d0f35a199d02d85c6fedc'

# 定义请求头
headers = {
    'Accept': 'application/json',  # 根据API要求选择合适的Accept类型，这里假设接受JSON格式
    'token': token  # 或者 'Bearer {token}'，取决于API规定的Token格式
}

# 定义数据库访问参数
config = {
    'host': '10.10.3.125',
    'port': 3306,
    'user': 'root',
    'passwd': 'root',
    'charset': 'utf8',
    'database': 'dolphinscheduler'
}
# 初始化打开数据库连接
mydb = MysqldbHelper(config)


def get_projects_list():
    """ 获取项目列表 """
    # 发送GET请求
    url_suffix = '/projects/list'
    response = requests.get(url_prefix + url_suffix, headers=headers)

    # 检查响应状态码等信息
    if response.status_code == 200:
        data = response.json()
        print(data)
    else:
        print(f"请求失败，状态码：{response.status_code}")


def projects_create(name, description):
    """ 创建项目
    发送POST请求 方法名称为projects_create, 然后再 Body 中配置所需的 projectName 和 description 参数
    """
    url_suffix = f'/projects?projectName={name}&description={quote_plus(description)}'
    response = requests.post(url_prefix + url_suffix, headers=headers)
    if response.status_code == 201:
        data = response.json()
        print(data)
    else:
        print(f"请求失败，状态码：{response.status_code}")


def get_project_code(name):
    result_tuple = mydb.select(tablename='t_ds_project', cond_dict={'name': name},
                               fields=['code'])
    return result_tuple[0][0]


def import_project_flow(project_name, file):
    """
    导入已定义好的工作流文件
    :param project_name:
    :param file:
    :return:
    """
    project_code = get_project_code(project_name)
    url_suffix = f'/projects/{project_code}/process-definition/import'
    files = {'file': file}
    response = requests.post(url_prefix + url_suffix, headers=headers, files=files)
    if response.status_code == 200:
        data = response.json()
        print(data)
        return project_code
    else:
        print(f"请求失败，状态码：{response.status_code}")
        return None


def upsert_token():
    """
    创建 或 更新 token
    :return:
    """
    res = mydb.select(tablename='t_ds_access_token', cond_dict={'token': token}, fields=['expire_time'])
    # 获取当前日期和时间
    current_time = datetime.now()
    expire_time = (current_time + timedelta(hours=1)).strftime('%Y-%m-%d %H:%M:%S')
    if res:
        # 如果存在，判断是否在有效期 不在有效期则 更新token
        if res[0][0] < current_time:
            # 更新token
            mydb.update(tablename='t_ds_access_token', cond_dict={'token': token},
                        attrs_dict={'expire_time': expire_time})
            print('更新token成功')
        else:
            print('token 有效')
    else:
        create_time = current_time.strftime('%Y-%m-%d %H:%M:%S')
        mydb.insert('t_ds_access_token',
                    {'user_id': '1',
                     'token': token,
                     'expire_time': expire_time,
                     'create_time': create_time,
                     'update_time': create_time})


def get_project_schedule_code(project_code):
    res1 = mydb.select(tablename='t_ds_process_definition', cond_dict={'project_code': project_code},
                       fields=['code'])
    process_definition_code = str(res1[0][0])

    res2 = mydb.select(tablename='t_ds_schedules', cond_dict={'process_definition_code': process_definition_code},
                       fields=['id'])
    schedule_id = res2[0][0]
    return process_definition_code, schedule_id


def project_schedule_online(project_code):
    """ 设置项目定时启动 """
    (process_definition_code, schedule_id) = get_project_schedule_code(str(project_code))
    url_suffix = f'/projects/{project_code}/schedules/{schedule_id}/online'
    response = requests.post(url_prefix + url_suffix, headers=headers)
    if response.status_code == 200:
        data = response.json()
        print(data)
    else:
        print(f"请求失败，状态码：{response.status_code}")


if __name__ == '__main__':
    project_name = 'content_marketing'
    upsert_token()
    # get_projects_list()
    projects_create(project_name, '内容营销管理平台工作流')
    project_code = import_project_flow(project_name, open('content_marketing_workflow.json', 'rb'))
    project_schedule_online(project_code)
